// pages/addStore/addStore.js
//获取应用实例
const app = getApp();
const api = require('../../utils/api');
const constant = require('../../utils/constant');
const storage = require('../../utils/storage');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //获取全局变量 导航栏的高度statusBarHeight
    statusBarHeight: app.globalData.statusBarHeight,
    // 胶囊
    jiaonang: app.globalData.jiaonang, 
    navigationHeight: app.globalData.navigationHeight,
    BASEURLWWW:constant.BASEURLWWW,
    BASEURL:constant.BASEURL,
    avatar_url: '',
    remarkNum: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },
  // 返回上一级
  back:function(){
    wx.reLaunch({
      url: '/pages/storeIndex/storeIndex',
    })
  },
  // 获取备注信息
  textareaChange(e){
    this.setData({
      remarkNum: e.detail.value.trim().length
    })
  },
  // 上传图片
  uploadImg(e){
    let that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success (res) {
        wx.uploadFile({
          url: `${that.data.BASEURL}/myfile/wechat`, //仅为示例，非真实的接口地址
          filePath: res.tempFilePaths[0],
          name: 'file',
          header:{
            'Authorization': 'Bearer '+ wx.getStorageSync(storage.LOCAL_JWT_KEY),
            'Deviceid': 'loveqing'
          },
          formData: {},
          success (res){
            let jsonObj = JSON.parse(res.data)
            if(jsonObj.code == 0){
              wx.showToast({
                title: '上传成功',
                icon: 'success'
              })
              that.setData({
                'avatar_url': jsonObj.data.uri
              })
            }else{
              wx.showToast({
                title: jsonObj.msg,
                icon: 'error'
              })
            }
            console.log(jsonObj);
          }
        })
      }
    })
  },
  // 添加仓库
  formSubmit(e){
    console.info(e.detail.value)
    let {store_name,store_address,remark} = e.detail.value
    if(store_name.trim() == ''){
      wx.showToast({
        title: '仓库名字不能为空',
        icon: 'none'
      })
      return
    }
    if(store_address.trim() == ''){
      wx.showToast({
        title: '仓库地址不能为空',
        icon: 'none'
      })
      return
    }
    api.addStore({
      store_name,
      store_address,
      remark,
      avatar_url:this.data.avatar_url
    }).then(res => {
      console.info(res)
      if(res.code == 0){
        wx.showToast({
          title: '成功',
          icon: 'success'
        })
        setTimeout(()=>{
          wx.reLaunch({
            url: '/pages/storeIndex/storeIndex',
          })
        },500)
      }else{
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  }
})